package Second;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ObjectMapper {

    public static String objectToJson(Object obj) {
        if (obj == null) {
            return "{}";
        }

        StringBuilder json = new StringBuilder("{");

        try {
            // 获取对象的Class对象
            Class<?> clazz = obj.getClass();

            Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                field.setAccessible(true);

                // 获取属性名和属性值
                String fieldName = field.getName();
                Object fieldValue = field.get(obj);

                json.append("\"").append(fieldName).append("\":")
                        .append(formatValue(fieldValue)).append(",");
            }

            if (json.length() > 1) {
                json.deleteCharAt(json.length() - 1);
            }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        json.append("}");
        return json.toString();
    }

    //格式化属性值为JSON格式
    private static String formatValue(Object value) {
        if (value == null) {
            return "null";
        }
        if (value instanceof String) {
            return "\"" + value + "\"";
        }
        return value.toString();
    }

    //将JSON字符串转换为指定类型的对象
    public static <T> T jsonToObject(String json, Class<T> clazz) {
        if (json == null || json.isEmpty()) {
            return null;
        }

        try {
            T instance = clazz.getDeclaredConstructor().newInstance();

            Map<String, String> keyValueMap = parseJsonToMap(json);

            Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                field.setAccessible(true);

                String fieldName = field.getName();

                if (keyValueMap.containsKey(fieldName)) {
                    // 获取JSON中的值并设置到对象属性中
                    String value = keyValueMap.get(fieldName);
                    setFieldValue(field, instance, value);
                }
            }

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //将JSON字符串解析为键值对
    private static Map<String, String> parseJsonToMap(String json) {
        Map<String, String> map = new HashMap<>();

        json = json.trim();
        if (json.startsWith("{")) {
            json = json.substring(1);
        }
        if (json.endsWith("}")) {
            json = json.substring(0, json.length() - 1);
        }

        // 分割键值对
        String[] pairs = json.split(",");
        for (String pair : pairs) {
            String[] keyValue = pair.split(":");
            if (keyValue.length == 2) {
                String key = keyValue[0].trim().replaceAll("\"", "");
                String value = keyValue[1].trim().replaceAll("\"", "");
                map.put(key, value);
            }
        }

        return map;
    }

    //设置字段值
    private static void setFieldValue(Field field, Object obj, String value) throws Exception {
        Class<?> fieldType = field.getType();

        if (fieldType == int.class || fieldType == Integer.class) {
            field.set(obj, Integer.parseInt(value));
        } else if (fieldType == double.class || fieldType == Double.class) {
            field.set(obj, Double.parseDouble(value));
        } else if (fieldType == boolean.class || fieldType == Boolean.class) {
            field.set(obj, Boolean.parseBoolean(value));
        } else if (fieldType == String.class) {
            field.set(obj, value);
        }
    }

    public static void main(String[] args) {
        // 示例对象
        class Person {
            private String name;
            private int age;

            @Override
            public String toString() {
                return "Person{name='" + name + "', age=" + age + "}";
            }
        }

        // 对象转JSON
        Person person = new Person();
        person.name = "张三";
        person.age = 40;
        String json = objectToJson(person);
        System.out.println("对象转JSON: " + json);

        // JSON转对象
        Person newPerson = jsonToObject(json, Person.class);
        System.out.println("JSON转对象: " + newPerson);
    }
}
